package com.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

@Controller
public class ExcelController {
    @RequestMapping("/excelFileUpload")
    public String readExcel(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("请求内容的长度为：" + request.getContentLength());
        System.out.println("请求内容的类型为：" + request.getContentType());


        // 1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        // 2、创建一个文件上传解析器
        diskFileItemFactory.setSizeThreshold(10);
//        setSizeThreshold方法用于设置是否将上传文件已临时文件的形式保存在磁盘的临界值（以字节为单位的int值），如果从没有调用
//        该方法设置此临界值，将会采用系统默认值10KB。对应的getSizeThreshold() 方法用来获取此临界值。

        //设置工厂的临时文件目录：当上传文件的大小大于缓冲区大小时，将使用临时文件目录缓存上传的文件
//        diskFileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        // 解决上传文件名的中文乱码
        servletFileUpload.setHeaderEncoding("UTF-8");


        //设置所有上传数据的最大值，单位字节long  10M
        servletFileUpload.setSizeMax(1024 * 1024 * 10);
        //设置单个文件上传的最大值
        servletFileUpload.setFileSizeMax(1024 * 1024 * 10);
        // 1. 得到 FileItem 的集合 items
        List<FileItem> list_fileItems;
        JSONObject jsonData = new JSONObject();
        JSONArray dataArr = new JSONArray();
        JSONObject dataObj = null;
        int flag = 0;
        try {
            list_fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : list_fileItems) {
                String fileName = fileItem.getName();
                //返回表单标签name属性的值
                String namede = fileItem.getFieldName();

                //保存上传文件到指定的文件路径
                InputStream is = fileItem.getInputStream();
                String Root_Path = "D:/MyDocument/Photo/";
                FileOutputStream fos = new FileOutputStream(Root_Path + fileName);
                System.out.println(Root_Path+fileName);
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) > 0) {
                    fos.write(buff);
                }
                is.close();
                fos.close();


                InputStream inputStream = fileItem.getInputStream();
                Workbook hssfWorkbook = WorkbookFactory.create(inputStream);
                // 第一个sheet空间
                Sheet hssfSheet = hssfWorkbook.getSheetAt(0);
                for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }
                    dataObj = new JSONObject();
                    //身份标识
                    Cell fdIdentify = hssfRow.getCell(0);
                    if (fdIdentify != null) {
                        dataObj.accumulate("fdIdentify", fdIdentify.toString());
                        System.out.print(fdIdentify.toString() + "    ");
                    } else {
                        dataObj.accumulate("fdIdentify", "");
                        System.out.print("    ");
                    }
                    //姓名
                    Cell fdName = hssfRow.getCell(1);
                    if (fdName != null) {
                        dataObj.accumulate("fdName", fdName.toString());
                    } else {
                        dataObj.accumulate("fdName", "");
                    }
                    //操作类型
                    Cell fdOperationType = hssfRow.getCell(2);
                    if (fdOperationType != null) {
                        dataObj.accumulate("fdOperationType", fdOperationType.toString());
                    } else {
                        dataObj.accumulate("fdOperationType", "");
                    }
                    //是否创建邮箱
                    Cell fdCreateMail = hssfRow.getCell(4);
                    if (fdCreateMail != null) {
                        dataObj.accumulate("fdCreateMail", fdCreateMail.toString());
                    } else {
                        dataObj.accumulate("fdCreateMail", "");
                    }
                    //有效期（年）
                    Cell fdExpireDate = hssfRow.getCell(5);
                    if (fdExpireDate != null) {
                        dataObj.accumulate("fdExpireDate", fdExpireDate.toString());
                    } else {
                        dataObj.accumulate("fdExpireDate", "");
                    }
                    //手机/电话号码
                    Cell fdMobileNo = hssfRow.getCell(6);
                    if (fdMobileNo != null) {
                        dataObj.accumulate("fdMobileNo", fdMobileNo.toString());
                    } else {
                        dataObj.accumulate("fdMobileNo", "");
                    }
                    //所属公司
                    Cell fdCompany = hssfRow.getCell(7);
                    if (fdCompany != null) {
                        dataObj.accumulate("fdCompany", fdCompany.toString());
                    } else {
                        dataObj.accumulate("fdCompany", "");
                    }
                    //地区
                    Cell fdRegion = hssfRow.getCell(8);
                    if (fdRegion != null) {
                        dataObj.accumulate("fdRegion", fdRegion.toString());
                    } else {
                        dataObj.accumulate("fdRegion", "");
                    }
                    //岗位
                    Cell fdStation = hssfRow.getCell(9);
                    if (fdStation != null) {
                        dataObj.accumulate("fdStation", fdStation.toString());
                    } else {
                        dataObj.accumulate("fdStation", "");
                    }
                    //SAP
                    Cell fdSap = hssfRow.getCell(10);
                    if (fdSap != null) {
                        dataObj.accumulate("fdSap", fdSap.toString());
                    } else {
                        dataObj.accumulate("fdSap", "");
                    }
                    //CRM
                    Cell fdCrm = hssfRow.getCell(11);
                    if (fdCrm != null) {
                        dataObj.accumulate("fdCrm", fdCrm.toString());
                    } else {
                        dataObj.accumulate("fdCrm", "");
                    }
                    //BPM
                    Cell fdBpm = hssfRow.getCell(12);
                    if (fdBpm != null) {
                        dataObj.accumulate("fdBpm", fdBpm.toString());
                    } else {
                        dataObj.accumulate("fdBpm", "");
                    }
                    //MDM
                    Cell fdMdm = hssfRow.getCell(13);
                    if (fdMdm != null) {
                        dataObj.accumulate("fdMdm", fdMdm.toString());
                    } else {
                        dataObj.accumulate("fdMdm", "");
                    }
                    //GSP
                    Cell fdGsp = hssfRow.getCell(14);
                    if (fdGsp != null) {
                        dataObj.accumulate("fdGsp", fdGsp.toString());
                    } else {
                        dataObj.accumulate("fdGsp", "");
                    }
                    //NEMS
                    Cell fdNems = hssfRow.getCell(15);
                    if (fdNems != null) {
                        dataObj.accumulate("fdNems", fdNems.toString());
                    } else {
                        dataObj.accumulate("fdNems", "");
                    }
                    //备注
                    Cell fdRemarks = hssfRow.getCell(16);
                    if (fdRemarks != null) {
                        dataObj.accumulate("fdRemarks", fdRemarks.toString());
                    } else {
                        dataObj.accumulate("fdRemarks", "");
                    }
                    dataArr.add(dataObj);
                }
            }
            flag = 1;
            jsonData.put("dataArr", dataArr);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            jsonData.put("error", e.toString());
        }
        jsonData.put("flag", flag);
        System.out.println(jsonData.toString());
        return jsonData.toString();
    }
}
